﻿using System;
using System.Collections.Generic;
using gms.security;
using gms.system;
using NHibernate.Criterion;

namespace gms.data {
	public class Player {
		public virtual int player_id { get; set; }
		public virtual string first_name { get; set; }
		public virtual string last_name { get; set; }
		public virtual string email { get; set; }
		public virtual byte[] password { get; set; }
		public virtual byte[] salt { get; set; }
		public virtual string address { get; set; }
		private IList<Acl_Group> groups { get; set; }

		public virtual void update_password(string pass) {
			password = Hashing.get_password_hash(pass, salt);
		}

		public virtual void load_groups() {
			groups = Player_Aclgroup.get_groups_of(player_id);
		}

		public virtual bool test(Acl_Type test_against) {
			bool retval = false;

			if (groups == null) {
				load_groups();
			}

			if (groups != null) {
				for (int i = 0; i < groups.Count; i++) {
					if (groups[i].test(test_against)) {
						retval = true;
					}
				}
			}

			return retval;
		}

		public virtual bool part_of_group(int id) {
			bool retval = false;

			if (groups == null) {
				load_groups();
			}

			if (groups != null) {
				for (int i = 0; i < groups.Count; i++) {
					if (groups[i].acl_id == id) {
						retval = true;
					}
				}
			}

			return retval;
		}

		public static bool email_exists(string email_to_check) {
			NHDatabase nhdb = new NHDatabase();
			int count = (int)nhdb.session.CreateCriteria<Player>().SetProjection(Projections.RowCount()).Add(Expression.Eq("email", email_to_check)).List()[0];
			nhdb.Dispose();

			return (count > 0);
		}
	}
}